package com.lanou.elh.sysmanage.item_manage.service.impl;

import com.lanou.elh.sysmanage.item_manage.entity.ItemCat;
import com.lanou.elh.sysmanage.item_manage.mapper.ItemCatMapper;
import com.lanou.elh.sysmanage.item_manage.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private ItemCatMapper itemCatMapper;


    private ItemCat selectItmCatById(Long id) {
        return itemCatMapper.selectItmCatById(id);
    }

    @Override
    public List<ItemCat> getItemCartList(Integer pId) {


        return itemCatMapper.selectItemCartListByPid(pId);
    }

    @Override
    public boolean addItemCategory(ItemCat itemCat) {
//        if (itemCat.getParentId() == 0) {
//            //根节点
        itemCat.setSortOrder(0);
        itemCat.setStatus(1);
        itemCat.setCreated(new Date());
        itemCat.setUpdated(new Date());
//        } else {
//            itemCat.setSortOrder(0);
//            itemCat.setStatus(1);
//            itemCat.setCreated(new Date());
//            itemCat.setUpdated(new Date());
//        }


        if (itemCatMapper.insert(itemCat) != 1) {
            System.out.println("添加商品分类失败");
            return false;
        }
        return true;
    }

    @Override
    public boolean updateItemCategory(ItemCat itemCat) {
        ItemCat oldItemCat = selectItmCatById(itemCat.getId());
        itemCat.setCreated(oldItemCat.getCreated());
        itemCat.setUpdated(new Date());

        if (itemCatMapper.updateById(itemCat) != 1) {
            System.out.println("修改商品分类失败");
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteItemCat(Long id) {
        //查询所有子节点
        List<ItemCat> childCat = getItemCartList(Math.toIntExact(id));
        if (childCat.size() > 0) {
            //有子节点，遍历删除
            for (ItemCat itemCat : childCat) {
                deleteItemCat(itemCat.getId());
            }
        }

        //如果没有子节点就直接删除
        if (itemCatMapper.deleteItemCatById(id) != 1) {
            System.out.println("删除商品分类失败");
            return false;
        }


        return true;
    }


}
